package converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.StrutsTypeConverter;

public class DateConverter extends StrutsTypeConverter{

	private DateFormat dateFormat;
	
	public DateFormat getDateFormat() {
		
		if(dateFormat==null) {
			
			ServletContext servletContext = ServletActionContext.getServletContext();
			
			String pattern=servletContext.getInitParameter("pattern");
			
			dateFormat = new SimpleDateFormat(pattern);
		}
		
		return dateFormat;
	}
	
	private Object ServletActionContext() {

		return null;
	}

	public DateConverter() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		
		if(toClass == Date.class) {
			
			if(values != null && values.length > 0) {
				
				String value=values[0];
				
				try {
					return getDateFormat().parseObject(value);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return values;
	}

	@Override
	public String convertToString(Map context, Object o) {
		
		if(o instanceof Date) {
			
			Date date = (Date) o;
			
			return getDateFormat().format(date);
		}
			
			
		return null;
	}

}
